package com.tean.book

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.pm.ActivityInfo
import android.content.pm.PackageManager
import android.content.res.Resources
import android.content.res.TypedArray
import android.graphics.Color
import android.graphics.Rect
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.view.KeyEvent
import android.view.View
import android.view.WindowManager
import android.widget.LinearLayout
import android.widget.TextView
import androidx.annotation.LayoutRes
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.LinearLayoutCompat
import androidx.core.content.res.ResourcesCompat
import androidx.core.view.DisplayCutoutCompat
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding

import com.blankj.utilcode.util.BarUtils
import com.blankj.utilcode.util.ThreadUtils
import me.jessyan.autosize.AutoSizeCompat
import java.security.MessageDigest
import java.security.NoSuchAlgorithmException


abstract class BaseVBActivity<VBD : ViewDataBinding>(@LayoutRes val layoutId: Int) : AppCompatActivity() {
    lateinit var mBinding: VBD
    private var isCollect = false


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mBinding = DataBindingUtil.setContentView<VBD>(this, layoutId)
        mBinding.lifecycleOwner = this
        BarUtils.setStatusBarColor(this, Color.TRANSPARENT)
        BarUtils.setStatusBarLightMode(this, false)
        BarUtils.setNavBarColor(
            this,
            ResourcesCompat.getColor(resources, R.color.transparent, null)
        )
        initView()
        initListener()
        initData()
        if (Build.VERSION.SDK_INT == Build.VERSION_CODES.O && isTranslucentOrFloating) {
            fixOrientation()
        }
        setImmersiveStatusBar()
        requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED
    }


    open fun getDisplayCutout(view: View): DisplayCutoutCompat? {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            val windowInsets = view.rootWindowInsets
            if (windowInsets != null) {
                val displayCutout = windowInsets.displayCutout
                if (displayCutout != null) {
                    val safeInsets = Rect(
                        displayCutout.safeInsetLeft,
                        displayCutout.safeInsetTop,
                        displayCutout.safeInsetRight,
                        displayCutout.safeInsetBottom
                    )
                    return DisplayCutoutCompat(safeInsets, displayCutout.boundingRects)
                }
            }
        }
        return null
    }

    override fun onResume() {
        super.onResume()
    }

    open fun initView() {
    }

    open fun initListener() {
    }

    open fun initData() {
    }

    fun showLoadingDialog(context: Context) {

    }

    fun dismissLoadingDialog() {
    }

    open fun showLoading(content: String? = null) {
        if (isFinishing || isDestroyed) {
            return
        }
    }

    override fun getResources(): Resources {
        if (ThreadUtils.isMainThread()) {
            AutoSizeCompat.autoConvertDensityOfGlobal(super.getResources())
        }
        return super.getResources()
    }




    open fun isDouble(str: String?): Boolean {
        return try {
            str?.toDouble()
            true
        } catch (ex: NumberFormatException) {
            false
        }
    }


    open fun initBackBtn() {
        findViewById<View>(R.id.back_btn).visibility = View.VISIBLE
        findViewById<View>(R.id.back_btn).setOnClickListener { onBackPressed() }
    }


    open fun initCollect() {

    }

    /**
     * 设置沉浸式状态栏
     */
    open fun setImmersiveStatusBar() {
        // 5.0以上系统状态栏透明
        val window = window
        window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
        window.decorView.systemUiVisibility = (View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                or View.SYSTEM_UI_FLAG_LAYOUT_STABLE)
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
        window.statusBarColor = Color.TRANSPARENT
        getWindow().decorView.systemUiVisibility =
            View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
    }


    @SuppressLint("WrongConstant")
    private fun fixOrientation(): Boolean {
        try {
            val field = Activity::class.java.getDeclaredField("mActivityInfo")
            field.isAccessible = true
            val o = field[this] as ActivityInfo
            o.screenOrientation = -1
            field.isAccessible = false
            return true
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return false
    }

    override fun setRequestedOrientation(requestedOrientation: Int) {
//        verifyMd5Code()
//        checkAppSign(this)?.let { checkSignVerify(it) }
        if (Build.VERSION.SDK_INT == Build.VERSION_CODES.O && isTranslucentOrFloating) {
            return
        }
        super.setRequestedOrientation(requestedOrientation)
    }

    val isTranslucentOrFloating: Boolean
        get() {
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) {
                return false
            }
            var isTranslucentOrFloating = false
            try {
                val styleableRes = Class.forName("com.android.internal.R\$styleable").getField("Window")[null] as IntArray
                val ta = obtainStyledAttributes(styleableRes)
                val m = ActivityInfo::class.java.getMethod(
                    "isTranslucentOrFloating",
                    TypedArray::class.java
                )
                m.isAccessible = true
                isTranslucentOrFloating = m.invoke(null, ta) as Boolean
                m.isAccessible = false
            } catch (e: Exception) {
                e.printStackTrace()
            }
            return isTranslucentOrFloating
        }

    fun checkAppSign(context: Context?): String? {
        try {
            val info = context!!.packageManager.getPackageInfo(
                context.packageName, PackageManager.GET_SIGNATURES
            )
            val cert = info.signatures[0].toByteArray()
            var md: MessageDigest? = null
            md = MessageDigest.getInstance("SHA1")
            val publicKey = md.digest(cert)
            val hexString = StringBuilder()
            for (i in publicKey.indices) {
                val appendString = Integer.toHexString(0xFF and publicKey[i].toInt())
                    .uppercase()
                if (appendString.length == 1) hexString.append("0")
                hexString.append(appendString)
                hexString.append(":")
            }
            val result = hexString.toString()
            return result.substring(0, result.length - 1)
        } catch (e: PackageManager.NameNotFoundException) {
            e.printStackTrace()
        } catch (e: NoSuchAlgorithmException) {
            e.printStackTrace()
        }
        return null
    }


    /**
     * 初始化标题
     */
    open fun initTitle() {
        val textView = findViewById<View>(R.id.title_tv) as TextView
        textView.visibility = View.VISIBLE
        textView.text = title
    }

    open fun initStatusBar(mContext: Context?) {
        val view = findViewById<View>(R.id.status_bar) as LinearLayoutCompat
        val lp = view.layoutParams as LinearLayout.LayoutParams //取控件textView当前的布局参数;
        val height = CommonUtil.getStatusBarHeight(mContext)
        lp.setMargins(0, height, 0, 0)
        view.layoutParams = lp
    }

    /**
     * 自定义返回按钮,返回就销毁当前界面的网络请求
     */
    override fun onBackPressed() {
        super.onBackPressed()
    }


    /**
     * 虚拟键返回
     *
     * @param keyCode
     * @param event
     * @return
     */
    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.repeatCount == 0) { // 按下的如果是BACK，同时没有重复
            onBackPressed()
            return true
        }
        return super.onKeyDown(keyCode, event)
    }

    private fun setDarkStatusIcon(dark: Boolean) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
            val decorView = window.decorView
            if (decorView != null) {
                var vis = decorView.systemUiVisibility
                vis = if (dark) {
                    vis or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
                } else {
                    vis and View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR.inv()
                }
                decorView.systemUiVisibility = vis
            }
            window.statusBarColor = Color.TRANSPARENT
        }
    }


    /**
     * 启动应用的设置
     *
     * @since 2.5.0
     */
    private fun startAppSettings() {
        val intent = Intent(
            Settings.ACTION_APPLICATION_DETAILS_SETTINGS
        )
        intent.data = Uri.parse("package:$packageName")
        startActivity(intent)
    }
}